package com.yinlei.hybridapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private Button showBtn;
    private Button showBtn2;
    private Button refreshBtn;
    private EditText editText;
    private MainActivity self;
    private NativeSDK nativeSDK = new NativeSDK(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        self = this;
        webView = findViewById(R.id.webView);
        refreshBtn = findViewById(R.id.refreshBtn);
        showBtn = findViewById(R.id.showBtn);
        showBtn2 = findViewById(R.id.showBtn2);
        editText = findViewById(R.id.editText);
        webView.loadUrl("http://192.168.8.115/js2native.html");//记得加网络权限,注意网络明文适配,加时间是为了防止页面缓存
        webView.getSettings().setJavaScriptEnabled(true);
//        webView.setWebChromeClient(new WebChromeClient(){
//            @Override
//            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//                if (!message.startsWith("jsbridge://")){
//                    return super.onJsAlert(view, url, message, result);
//                }
//                //是自定义的一个urlscheme
//                String text = message.substring(message.indexOf("?")+1);
//                self.showNativeDialog(text);
//                result.confirm();
//                return true;
//            }
//        });

        //第2种实现方式
        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new NativeBridge(this), "NativeBridge");//注入js API

        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputValue = editText.getText().toString();
                self.showWebDialog(inputValue);
            }
        });
        showBtn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nativeSDK.getWebEditTextValue(new Callback() {
                    @Override
                    public void invoke(String value) {
                        new AlertDialog.Builder(self).setMessage("Web 输入值："+value).create().show();
                    }
                });
            }
        });


        refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {// 重新加载
                webView.loadUrl("http://192.168.8.115/js2native.html");//记得加网络权限,注意网络明文适配,加时间是为了防止页面缓存
            }
        });

    }

    private void showNativeDialog(String text){
        new AlertDialog.Builder(self).setMessage(text).create().show();
    }

    private void showWebDialog(String text){//原生端调用web端
        String jsCOde = String.format("window.showWebDialog('%s')",text);
        webView.evaluateJavascript(jsCOde,null);
    }


    interface Callback{
        void invoke(String value);
    }
    class NativeSDK {
        private int id  = 1;
        private Context context;
        private Map<Integer, Callback> callbackMap= new HashMap<>();
        NativeSDK(Context context){
            this.context = context;
        }

        void getWebEditTextValue(Callback callback){
            int callbackId = id++;
            callbackMap.put(callbackId,callback);
            final String jsCode = String.format("window.JSSDK.getWebEditTextValue(%s)",callbackId);
            ((MainActivity)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((MainActivity)context).webView.evaluateJavascript(jsCode,null);
                }
            });
        }

        void receiveMessage(int callbackId, String value){
            if(callbackMap.containsKey(callbackId)){
                callbackMap.get(callbackId).invoke(value);
            }
        }
    }


    class NativeBridge{
        private Context context;
        public NativeBridge(Context context) {
            this.context = context;
        }
        @JavascriptInterface
        public void showNativeDialog(String text){
            new AlertDialog.Builder(context).setMessage(text).create().show();
        }

        @JavascriptInterface
        public void getNativeEditTextValue(int callbackId){
            final MainActivity mainActivity = (MainActivity) context;
            String value = mainActivity.editText.getText().toString();
            final String jsCode = String.format("window.JSSDK.receiveMessage('%s','%s')",callbackId,value);
            mainActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mainActivity.webView.evaluateJavascript(jsCode,null);
                }
            });
        }

        @JavascriptInterface
        public void receiveMessage(int callbackId, String value){
            ((MainActivity)context).nativeSDK.receiveMessage(callbackId, value);
        }

    }

}
